package zheezes.eisp.compute.model;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;

import zheezes.eisp.data.orm.CalcTask;
import zheezes.eisp.data.orm.Concentrator;
import zheezes.eisp.data.orm.Ct;
import zheezes.eisp.data.orm.Pt;
import zheezes.eisp.data.orm.ResMeterDailyUse;
import zheezes.eisp.data.orm.ResMeterExt;
import zheezes.util.DateFormatUtil;


public class ConResMeterDailyUseCalcTaskHandler extends CalcTaskHandler {
	private static Logger logger = Logger.getLogger(ConResMeterDailyUseCalcTaskHandler.class);
	
	public void run() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(task.getDate());		
		List<ResMeterExt> list = dataAccessor.queryConNeedCalcDailyUseResMeter(task.getTargetId(), cal.getTime());
		Concentrator con = dataAccessor.getConById(task.getTargetId());
		logger.debug(String.format("There is %d meter in %s need to calc daily use at %s", list.size(), con.getLogicAddr(), DateFormatUtil.getDateFmt().format(task.getDate())));
		int scnt = 0;
		for (ResMeterExt mt : list) {
			if (!terminated) {
				Ct ct = dataAccessor.getCtById(mt.getCp());
				Pt pt = dataAccessor.getPtById(mt.getTp());
				if(ct != null && pt != null) {
					ResMeterDailyUse du = new ResMeterDailyUse();
					du.setType(ResMeterDailyUse.TYPE_RES_METER);
					du.setMpId(mt.getMpId());
					du.setDate(cal.getTime());
					BigDecimal tpp = mt.getNpp();
					BigDecimal bpp = mt.getPp();
					BigDecimal ppu = tpp.subtract(bpp);
					ppu = ppu.multiply(new BigDecimal(ct.getDeno())).divide(new BigDecimal(ct.getBase()));
					ppu = ppu.multiply(new BigDecimal(pt.getDeno())).divide(new BigDecimal(pt.getBase()));
					du.setPp(ppu);
					if (dataAccessor.saveResMeterDailyUse(du) == 0) {
						scnt++;
					} else {
						logger.warn(String.format("save resident meter[mpid = %d, no = %s] daily use failure", mt.getMpId(), mt.getNo()));
					}
				}
			} else {
				logger.info("terminated when traverse resident meter");
				break;
			}
		}
		if(scnt > 0) {
			condChecker.checkZoneLineLose(con.getGid(), cal);
		}
		/**
		 * may be there is no meter need to calc
		 */
		if(scnt == list.size()) {
			task.setStatus(CalcTask.STATUS_FINISH);
			dataAccessor.updateCalcTask(task);
		}
	}
	
	public void desc() {
		logger.debug(String.format("task date = %s", DateFormatUtil.getDateFmt().format(task.getDate())));
	}
}
